import React, { useEffect, useState } from "react";
import '../../appcommon.css';
import styles from './login.module.css';
import Input from "@/components/Input";
import { useFormik } from "formik";
import { useDispatch } from "react-redux";
import { DotLoading, Mask } from "antd-mobile";
import { doLogin } from "@/store/actions/login";
import { useHistory } from "react-router-dom/cjs/react-router-dom";
import icon_login_user from '@/assets/icon_login_user.png'
import icon_login_lock from '@/assets/icon_login_lock.png'
import { removeUserInfo } from "@/utils/storage";
import { saveEvent } from "@/store/actions/saveEvent";
import { LangThai } from "@/utils/langThai";

/**
 * 登录页
 */
export default function Login() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    // 文案翻译
    const [curLang, setCurLang] = useState(LangThai);

    //router
    const history = useHistory()

    // const location = useLocation()

    // 获取 Redux 分发器
    const dispatch = useDispatch()

    //清空登录信息
    useEffect(() => {
        console.log("LOGIN-移除登录信息")
        //移除登录信息
        removeUserInfo()

        //打点
        doHitEvent("LOGIN_START")

        return () => {
            //打点
            doHitEvent("LOGIN_END")
        }
    }, [])

    // Formik 表单对象
    const form = useFormik({
        //设置表单初始值
        initialValues: {
            mobile: '',
            password: ''
        },

        //提交
        onSubmit: values => {
            console.log(values)

            //提交登录
            onLoginSubmit()
        },

        //校验
        validate(values) {
            const errors = {}
            // 非空
            if (!values.mobile || values.mobile === '') {
                errors.mobile = '请输入正确格式的号码';
            }

            if (!values.password || values.password === '' || (values.password.length < 8)) {
                errors.password = '请输入正确格式的密码';
            }

            return errors
        }
    });

    //请求登录接口
    const doUserLogin = async (mobile, password) => {
        console.log("doUserLogin: " + mobile + " , " + password);

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = doLogin(mobile, password, onDoUserLoginCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 登录返回
    const onDoUserLoginCallback = (success, data) => {
        //关闭loading
        setMaskVisible(false)
        console.log('登录返回: ' + success);

        if (success && data) {
            // 如果是尼日版本，直接转全流程
            console.log('跳转首页');
            history.replace('/home')
        }
    };

    //点击登录
    const onLoginSubmit = async () => {
        try {
            //打点
            doHitEvent("LOGIN_COMMIT_CLICK")

            let inputResult = isInputCorrect();
            console.log(inputResult);
            if (!inputResult) return;

            // 登录
            doUserLogin(inputResult.mobile, inputResult.password);

        } catch (e) {
            console.log(e)
        }
    }

    // 判断输入是否合法
    const isInputCorrect = () => {
        //验证手机号
        let mobile = form.values.mobile;

        //验证密码
        let password = form.values.password;

        console.log('m: ' + mobile + ", p:" + password);


        if (!mobile || (mobile.length <= 0)) {
            return null;
        }

        if (!password || (password.length < 8)) {
            return null;
        }

        return { mobile: mobile, password: password };
    };

    return (
        <div className='pageRoot'>
            {/* <NavigateBar theme="white" showLogout={false} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}></NavigateBar> */}

            {/* 使用添加 home screen bar */}
            {/* <AddFavorite onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} /> */}

            <div className="pageContentColumn contentHorizontalPadding pageMarginTop16px">

                <form className="pageContentColumn pageMarginTop16px" onSubmit={form.handleSubmit}>

                    {/* 手机号码输入框 */}
                    <div className={styles.loginVerifyInput}>
                        <Input
                            id="mobile"
                            title='手机号'
                            icon={icon_login_user}
                            name="mobile"
                            placeholder='请输入'
                            type="text"
                            value={form.values.mobile}
                            onBlur={form.handleBlur}
                            onChange={form.handleChange}
                            autoComplete="off" />
                    </div>
                    {form.errors.mobile && form.touched.mobile && (
                        <div className={styles.loginValidate}>{form.errors.mobile}</div>
                    )}

                    {/* 昵称框 */}
                    {/* <div className={styles.loginVerifyInput}>
                        <Input
                            id="password"
                            title='昵称'
                            name="name"
                            icon={icon_login_lock}
                            placeholder='请输入'
                            type="text"
                            value={form.values.name}
                            onBlur={form.handleBlur}
                            onChange={form.handleChange}
                            autoComplete="off" />
                    </div>
                    {form.errors.name && form.touched.name && (
                        <div className={styles.loginValidate}>{form.errors.name}</div>
                    )} */}

                    {/* 密码输入框 */}
                    <div className={styles.loginVerifyInput}>
                        <Input
                            id="password"
                            title='密码'
                            name="password"
                            icon={icon_login_lock}
                            placeholder='请输入'
                            type="text"
                            value={form.values.password}
                            onBlur={form.handleBlur}
                            onChange={form.handleChange}
                            autoComplete="off" />
                    </div>
                    {form.errors.password && form.touched.password && (
                        <div className={styles.loginValidate}>{form.errors.password}</div>
                    )}
                </form>

                {/* 登录提交 */}
                <div className={`pageBtnSubmit pageMarginTop26px ${(form.isValid && form.dirty) ? '' : "disabled"}`} onClick={form.handleSubmit} >登录</div>

                {/* 底部 margin */}
                <div className="pageBottomEdge"> </div>

                {/* load mask */}
                <Mask visible={maskVisible} opacity={0.1}
                    onMaskClick={() => { }}>
                    <div className="pageLoadingOverlayContent">
                        <span style={{ fontSize: 24, color: '#3498DB' }} >
                            <DotLoading color="currentColor" />
                        </span>
                    </div>
                </Mask>
            </div>
        </div >
    )
}